﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DreamBuilder.UI.UserControls.DataAccess;
using DreamBuilder.UI.UserControls.DataAccess.Services;
using DreamBuilder.Core.Container;
using System.Data;
using Microsoft.Practices.Unity;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using DreamBuilder.Common;
using System.ComponentModel;

namespace DreamBuilder.UI.UserControls
{
    public partial class AttachmentManager : ControlBase
    {
        public string ObjectID
        {
            set
            {
                ViewState["ObjectID"] = value;
            }
            get
            {
                if (ViewState["ObjectID"] == null)
                {
                    return String.Empty;
                }
                return (string)ViewState["ObjectID"];
            }
        }

        public string ObjectTableName
        {
            set
            {
                ViewState["ObjectTableName"] = value;
            }
            get
            {
                if (ViewState["ObjectTableName"] == null)
                {
                    return String.Empty;
                }
                return (string)ViewState["ObjectTableName"];
            }
        }

         public string AttachmentDBHelperString
        {
            get
            {
                if (ViewState["DBHelperString"] == null) 
                {

                    EPPage page = HttpContext.Current.Handler as EPPage;
                    if (page != null && !string.IsNullOrEmpty(page.DBHelpName))
                    {
                        return  page.DBHelpName;
                    }
                }
                return ViewState["DBHelperString"].ToString();
            }
            set
            {
                ViewState["DBHelperString"] = value;
            }
        }
        /// <summary>
        /// 附件类型//ADD By YSP 2011-07-25
        /// </summary>
         public string FunctionID
         {
             set
             {
                 ViewState["FunctionID"] = value;
             }
             get
             {
                 if (ViewState["FunctionID"] == null)
                 {
                     return String.Empty;
                 }
                 return (string)ViewState["FunctionID"];
             }
         }

        /// <summary>
        /// 是否操作后清空附件列表
        /// </summary>
         [DefaultValue(false)]
         public bool Refresh
         {
             set;
             get;
         }

        /// <summary>
        /// 默认支持的类型,以*.jpg为类型格式，多重类型以逗号隔开，例如：*.jpg,*.bmp .默认为*.*  支持全部格式
        /// </summary>
        [DefaultValue("*.*")]
         public string DefaultType
         {
             get;
             set;
         }

        [Dependency]
        public AttachmentDAL attachmentDAL
        {
            get
            {
                AttachmentDAL attachmentDAL = UContainer.Resolve<AttachmentDAL>();
                attachmentDAL.AttachmentDBHelperString = AttachmentDBHelperString;
                return attachmentDAL;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //注册文件
            RegistFiles();
            //生成swfupload路径
            CreateApplicationPath();
            //SetMyViewStateID();
            InitJsCultureInfo();
            //设置标题多语
            SetTitleText();
            AttachmentUploadFileInfo uf = new AttachmentUploadFileInfo();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AttachmentUploadFileInfo));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms, uf);
            this.Bind();

            if (!IsPostBack)
            {
                this.hidAttachmentAddList.Value = string.Empty;
                this.hidAttachmentDeleteList.Value = string.Empty;
                ShowAttachments();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ReFreshload();
        }

        public void ReFreshload()
        {
            if (!this.Refresh)
            {
                ShowAttachments();
            }
            else
            {
                this.hidAttachmentAddList.Value = string.Empty;
                this.hidAttachmentDeleteList.Value = string.Empty;
                ShowAttachments();
                this.Refresh = false;
            }
        }

        private void SetTitleText()
        {
            this.litAttachmentTitle.Text = GetString("attachment");
        }


        private void ShowAttachments()
        {
            DataTable dt = attachmentDAL.GetAttachmentList(this.ObjectID, this.ObjectTableName, this.hidAttachmentAddList.Value, this.hidAttachmentDeleteList.Value, this.FunctionID);
            if (dt != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<script>");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("AddAttachment('" + dr["AttachmentID"].ToString() + "','" + dr["AttachmentName"].ToString().Replace("'",@"\'") + "','" + dr["AttachmentSize"].ToString() + "','" + Convert.ToDateTime(dr["UploadTime"]).ToString("yyyy-MM-dd HH:mm:ss") + "','" + this.hidAttachmentDeleteList.ClientID + "','" + this.AttachmentTable.ClientID + "','" + AttachmentDBHelperString + "','" + this.DisableUploadAndDelButton + "');");
                }
                sb.Append("</script>");
                Page.ClientScript.RegisterStartupScript(this.GetType(), "attachmentDataList" + this.FunctionID, sb.ToString());
            }
        }

        private void InitJsCultureInfo()
        {
            base.ControlPath = "UserControls/AttachmentManager";
            StringBuilder sb = new StringBuilder();
            sb.Append("<script>");
            sb.Append(" var resBtnSelectFile = '" + GetString("BtnSelectFile") + "'; \n");
            sb.Append(" var resAlertZeroFile = '" + GetString("AlertZeroFile") + "'; \n");
            sb.Append(" var resAlertBigFile = '" + GetString("AlertBigFile") + "'; \n");
            sb.Append(" var resUploadSuccess = '" + GetString("UploadSuccess") + "'; \n");
            sb.Append(" var resUploadPercentage = '" + GetString("UploadPercentage") + "'; \n");
            sb.Append(" var currentCulture = '" + base.GetCurrentCulture + "'; \n");
            sb.Append("</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "attachmentResInfo", sb.ToString());
        }


        private void Bind()
        {
            TableHeaderRow trheader = new TableHeaderRow();
            trheader.CssClass = "AT-Header";
            this.AttachmentTable.Rows.Add(trheader);

            //文件名列
            TableHeaderCell tcFileName = new TableHeaderCell();
            tcFileName.Text = GetString("fileName");
            tcFileName.CssClass = "AT-Header-FileName";
            trheader.Cells.Add(tcFileName);
            //文件大小列
            TableHeaderCell tcFileSize = new TableHeaderCell();
            tcFileSize.Text = GetString("fileSize");
            tcFileSize.CssClass = "AT-Header-FileSize";
            trheader.Cells.Add(tcFileSize);
            //文件上传日期列
            TableHeaderCell tcFileDate = new TableHeaderCell();
            tcFileDate.Text = GetString("fileDate");
            tcFileDate.CssClass = "AT-Header-FileDate";
            trheader.Cells.Add(tcFileDate);

            //文件上传状态
            TableHeaderCell tcFileUploadStatus = new TableHeaderCell();
            tcFileUploadStatus.Text = GetString("uploadStatus");
            tcFileUploadStatus.CssClass = "AT-Header-FileUploadStatus";
            trheader.Cells.Add(tcFileUploadStatus);
            //删除按钮列
            TableHeaderCell tcFileDelete = new TableHeaderCell();
            tcFileDelete.Text = GetString("btnDelete");
            tcFileDelete.CssClass = "AT-Header-FileDelete";
            trheader.Cells.Add(tcFileDelete);
      
        }



        /// <summary>
        /// 生成swfupload.swf路径
        /// </summary>
        private void CreateApplicationPath()
        {
            string path = "<script>var applicationPath ='" + System.Web.HttpContext.Current.Request.ApplicationPath + "';</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "applicationPath", path);
        }

        /// <summary>
        /// 注册文件
        /// </summary>
        private void RegistFiles()
        {
            //注册脚本文件
            string swfupload = System.Web.HttpContext.Current.Request.ApplicationPath + "/Javascript/swfupload.js";
            string handlers = System.Web.HttpContext.Current.Request.ApplicationPath + "/Javascript/Attachment.js";
            string json2 = System.Web.HttpContext.Current.Request.ApplicationPath + "/Javascript/json2.js";
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "swfupload", swfupload);
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "handlers", handlers);
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "json2", json2);
            //注册css样式文件
            string cssSWFUpload = "<link href=\"" + System.Web.HttpContext.Current.Request.ApplicationPath + "/Styles/UCAttachment1.css\" rel=\"stylesheet\" type=\"text/css\" />";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "cssSWFUpload", cssSWFUpload);
        }

        public DataTable GetSaveDataTable(string ObjectID, string ObjectTableName)
        {
            DataTable dt = this.attachmentDAL.GetSaveDataTable(ObjectID, ObjectTableName, this.hidAttachmentAddList.Value, this.hidAttachmentDeleteList.Value);
            return dt;
        }


        /// <summary>
        /// 获取与SWFUpload控件组合后的控件Id
        /// </summary>
        /// <param name="id">副Id</param>
        /// <returns></returns>
        protected string GetControlId(string id)
        {
            return string.Format("{0}_{1}", this.ID, id.Trim());
        }

        private string disableUploadAndDelButton = "false";

        public string DisableUploadAndDelButton
        {
            get
            {
                if (!string.IsNullOrEmpty(this.disableUploadAndDelButton) && this.disableUploadAndDelButton.Trim().ToLower() == "true")
                {
                    return "true";
                }
                else
                {
                    return "false";
                }
            }
            set
            {
                this.disableUploadAndDelButton = value;
            }
        }
    }
}